from django.http import FileResponse
from rest_framework.response import Response
from rest_framework.viewsets import ReadOnlyModelViewSet, GenericViewSet
from gxun_news.settings import NEWS_DOCX_ROOT
from news.models import NewsModel
from news.serializers import NewSerializer
from utils.get_gxun_news import Get_gxun_news
from rest_framework.status import HTTP_400_BAD_REQUEST

class GetNewsDocxView(GenericViewSet):
    get_gxun_news = Get_gxun_news()

    # 得到第一页所有新闻 初始化 过程较长
    def all_one_news(self, request):
        try:
            all_list = self.get_gxun_news.get_all_news()
        except Exception as e:
            return Response({'error': e})
        for list_data in all_list:
            news_title_content = list_data.get('news_title_content')
            release_time = list_data.get('release_time')
            is_exist = NewsModel.objects.filter(news_title_content=news_title_content, release_time=release_time)
            if not is_exist:
                NewsModel.objects.create(news_title_content=news_title_content, release_time=release_time)
        self.get_gxun_news.all_list.clear()
        return Response({'msg': '初始化完成'})

    # 得到或刷新文件内今日新闻
    def all_today_news(self, request):
        try:
            all_list = self.get_gxun_news.get_today_news()
        except Exception as e:
            return Response({'error': e})
        if not all_list:
            return Response({'msg': '今日无更新'})
        for list_data in all_list:
            news_title_content = list_data.get('news_title_content')
            release_time = list_data.get('release_time')
            is_exist = NewsModel.objects.filter(news_title_content=news_title_content, release_time=release_time)
            if not is_exist:
                NewsModel.objects.create(news_title_content=news_title_content, release_time=release_time)
        self.get_gxun_news.all_list.clear()
        return Response({'msg': '加载今日新闻完成'})

    # 得到 docx文件
    def post_docx(self, request):
        news_title_content = request.data.get('news_title_content')
        filename = f"{NEWS_DOCX_ROOT}/{news_title_content}.docx"
        try:
            file = open(filename, 'rb')
        except:
            return Response({'error': 'docx文件不存在', 'status_code': HTTP_400_BAD_REQUEST})
        response = FileResponse(file)
        response['Content-Type'] = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
        response['Content-Disposition'] = 'attachment;filename= ' + '文件'.encode('utf-8').decode('ISO-8859-1') + '.docx'
        return response


class NewsView(ReadOnlyModelViewSet):
    queryset = NewsModel.objects.all()
    serializer_class = NewSerializer
